package jalus.dao;

import jalus.model.File;
import jalus.model.PMF;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class FileDAO {
	public File getFileById(Long id){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.setDetachAllOnCommit(true);
		File file;
		try{
			file = pm.getObjectById(File.class, id);
		}finally{
			pm.close();
		}
		return file;
	}
	public Long add(File file){
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Long id = null;
        try {
            id = new Long(pm.makePersistent(file).getId());
        } finally {
            pm.close();
        }
        return id;
	}
	
	@SuppressWarnings("unchecked")
	public List<File> getAllFile(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(File.class);
	    query.setOrdering("date desc");
	    List<File> fileList;
	    try{
	    	fileList = (List<File>) query.execute();
	    }finally{
	    	query.closeAll();
	    }
	    return fileList;
	}
	
	@SuppressWarnings("unchecked")
	public List<File> getRangeFile(int startpos, int endpos){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.setDetachAllOnCommit(true);
	    Query query = pm.newQuery(File.class);
	    query.setOrdering("date desc");
	    query.setRange(startpos, endpos);
	    List<File> fileList;
	    try{
	    	fileList = (List<File>) query.execute();
	    }finally{
	    	query.closeAll();
	    }
	    return fileList;
	}
	
	public void deleteFileById(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		File file = pm.getObjectById(File.class, id);
		try{
			pm.deletePersistent(file);
		}finally{
			pm.close();
		}
	}
}
